/**
 * var options = {
 *  maxHeight : 1000,
 *  maxWidth : 1000,
 *  container : htmlNode,  操作图片预览的container，如果没有则默认追加到body
 * }
 * 
 * var options = {container: document.getElementById("mypreview")};
 * 
 * //打开并显示图片，并可以进行截图
 * var viewUploader = new ViewUploader(options);
 * var first = true;
 *   function openFile(){
 *       if(!first){
 *           viewUploader.clear();
 *       }
 *       first = false;
 *       viewUploader.selectFile();
 *   }
 *  
 * //获取截取部分的base64，如果截取，则返回全部
 *  viewUploader.cutAsBase64();
 * 
 *  在指定的位置显示截图, 如果为true则是追加显示，
 *  viewUploader.cutAsView(document.getElementById("preview"), true);
 * */
var ViewUploader = function(options){
	var _this = this;
	if(!options){
		options = {};
	}
	
	//工具类
	_this.kit = {
		//绑定事件
		bindEvent: function(type, node, func){
			if(window.addEventListener){ // Mozilla, Netscape, Firefox
				node.removeEventListener(type, func, false);
				node.addEventListener(type, func, false);
				
			} else { // IE
				node.detachEvent('on'+type, func);
				node.attachEvent('on'+type,  func);
			}
		},
		//添加CSS
		addCss : function (node, styles){
			for(var key in styles){
				node.style[key]=styles[key];
			}
		}, 
		clearCanvas: function(canvas){
			var ctx=canvas.getContext("2d");
			//cxt.clearRect(x,y, width,height);  
			ctx.clearRect(0,0,canvas.width,canvas.height);
		},
		clearRect: function(canvas, x, y, width, height) 
		{  
			var ctx=canvas.getContext("2d");
			ctx.clearRect(x,y, width,height);  
		},
		getLocation : function (e) {
			return {
				x: e.x || e.clientX,
				y: e.y || e.clientY
			}
		}, 
		// 把image 转换为 canvas对象  
		convertImageToCanvas : function(image, width, height) {  
			// 创建canvas DOM元素，并设置其宽高和图片一样   
			var canvas = document.createElement("canvas");  
			canvas.width = width;  
			canvas.height = height;  
			// 坐标(0,0) 表示从此处开始绘制，相当于偏移。  
			canvas.getContext("2d").drawImage(image, 0, 0, width, height);    
			return canvas; 
		}   
	}

	_this.wrapper = null;
	_this.imgCanvas = null;
	_this.ctrlCanvas = null;
	_this.tip = null;
	_this.input = null;
	_this.img = null;
	_this.maxWidth = options.maxWidth || 1000;
	_this.maxHeight = options.maxHeight || 1000;
	_this.mouseWhere = "canvase"; //rectDiv;
	_this.rectInfo = {x:0,y:0, w:0, h:0};
	createContainer();

	_this.selectorDiv = null;
	_this.childrenSelector = {};
	_this.currSelectorInfo = {x:0, y:0, type: ""}

	//添加文本框
	_this.selectFile = function(){
		var input = document.createElement("input");
		input.type="file";
		input.style.display="none";
		_this.container.appendChild(input);
		input.click();

		_this.kit.bindEvent("change", input, function(e){
			inputChange(this, e);
		});
		
	}
	
	//剪切文件,返回base64
	_this.cutAsBase64 = function(){
		if(!_this.imgCanvas){
			console.log("没有图像内容");
			return false;
		}
		
		var dataurl = null;
		if(_this.rectInfo.w==0 || _this.rectInfo.h==0){
			dataurl = _this.imgCanvas.toDataURL('image/jpeg');
		}else{
			var canvas = document.createElement('canvas');
			var context = canvas.getContext('2d');
			canvas.width = _this.rectInfo.w;
			canvas.height = _this.rectInfo.h;
			context.drawImage(_this.imgCanvas, _this.rectInfo.x, _this.rectInfo.y, _this.rectInfo.w, _this.rectInfo.h, 0, 0, _this.rectInfo.w, _this.rectInfo.h);
			dataurl = canvas.toDataURL();
		}
		return dataurl;
	}
	
	//剪切文件并预览到指定的容器里
	//返回canvas
	_this.cutAsView = function(container, append){
		if(!_this.imgCanvas){
			console.log("没有图像内容");
			return null;
		}
		
		if(container && !append){
			var count = container.length;
			for(var i = count-1; i>-1; i--)
				container.removeChild(container.children[i]);
		}

		if(_this.rectInfo.w!=0 && _this.rectInfo.h!=0){
			var canvas = document.createElement('canvas');
			var context = canvas.getContext('2d');
			canvas.width = _this.rectInfo.w;
			canvas.height = _this.rectInfo.h;
			context.drawImage(_this.imgCanvas, _this.rectInfo.x, _this.rectInfo.y, _this.rectInfo.w, _this.rectInfo.h, 0, 0, _this.rectInfo.w, _this.rectInfo.h);
			container.appendChild(canvas);
			return canvas;
		}
		return null;
	}
	
	_this.clear = function(){
		//_this.container.parentNode.removeChild(_this.container);
		var children = _this.container.children;
		var deletes = [];
		for(var i=0; i<children.length; i++){
			if(children[i].tagName.toLocaleLowerCase() == "div"){
				deletes.push(children[i]);
			}
		}
		for(var index in deletes){
			_this.container.removeChild(deletes[index]);
		}
	}
	
	function createContainer(){
		_this.container = options.container;
		if(!_this.container){
			_this.container = document.createElement("div");
			_this.container.id="viewer-wrapper-102912";
			_this.kit.addCss(_this.container, {"position":"relative"});
			document.body.appendChild(_this.container);
		}
	}

	//文件选择事件，
	function inputChange(input, event){
		var file = input.files[0];
		if (!file) return;

		var ext = ""; 
		var index = file.name.lastIndexOf(".");
		if(index> -1){
			ext = file.name.substring(index).toLocaleLowerCase();
		}

		var types = [".jpg", ".png", ".gif", ".jpeg"];
		if(types.indexOf(ext)<0){
			console.info("只支持jpg, png, gif格式的图片");
			return ;
		}

		//write 2 canvas
		writeToCanvas(event);


	}//end inputChange
	
	//将图片转还为canvas,并构建基本的操作环境
	function writeToCanvas(event){
		var reader = new FileReader();
		_this.img = new Image();
		reader.readAsDataURL(event.target.files[0]);

		// 读文件成功的回调
		reader.onload = function(e) {
			// e.target.result就是图片的base64地址信息
			_this.img.src = e.target.result;
			_this.img.onload = function(e){
				var width = _this.img.width, height=_this.img.height;
				if(width>height){
					if(width>_this.maxWidth){
						var ratio = width / 1000;
						_this.maxWidth = 1000;
						_this.maxHeight = height / ratio;
					}
				}else{
					if(height > _this.maxHeight){
						var ratio = height / 1000;
						_this.maxHeight = 1000;
						_this.maxWidth = width / ratio;
					}

				}
				
				_this.imgCanvas = _this.kit.convertImageToCanvas(_this.img, _this.maxWidth, _this.maxHeight );
				
				_this.wrapper = document.createElement("div");
				var id = "canvas-wrapper-1002";
				_this.wrapper.id=id;
				_this.kit.addCss(_this.wrapper, {"position":"relative"});
				_this.wrapper.appendChild(_this.imgCanvas);
				_this.container.appendChild(_this.wrapper);
				
				_this.ctrlCanvas =  document.createElement("canvas"); 
				_this.ctrlCanvas.id="ctrl-1002";
				_this.kit.addCss(_this.ctrlCanvas, {"position":"absolute", "top":"0px", "left":"0px"});
				//ctrlCanvas.style.background="rgba(0,0,0,0.3)"; 
				_this.ctrlCanvas.width = _this.maxWidth;  
				_this.ctrlCanvas.height = _this.maxHeight;
				_this.wrapper.appendChild(_this.ctrlCanvas);

				 _this.ctrlCanvas.onmousedown = function(e) {
					 ctrlCanvasMouseDown(e, this);
				 }

			}
		}

	}//end write to canvas

	function ctrlCanvasMouseDown(e, canvas){
		_this.mouseWhere = "canvas";
		 
		//删除控制图层
		var children = _this.wrapper.children;
		var deletes = [];
		for(var i=0; i<children.length; i++){
			if(children[i].tagName.toLocaleLowerCase() == "div"){
				deletes.push(children[i]);
			}
		}
		for(var index in deletes){
			_this.wrapper.removeChild(deletes[index]);
		}

		//获取鼠标当前坐标 
		var pageX = e.clientX;
		var pageY = e.clientY;
		//获取block的坐标，左边界和上边界 
		//var offX = parseInt(canvas.style.left) || 0;
		//var offY = parseInt(canvas.style.top) || 0;
		var offX = e.offsetX;
		var offY = e.offsetY;

		//计算出鼠标坐标相对于block坐标的间距 
		//var offLX = pageX - offX;
		//var offLY = pageY - offY;
		var offLX = offX;
		var offLY = offY;
		//console.log("mousedown: x="+offLX+", y="+offLY);
		
		document.onmousemove = function(event) {
			docMouseMove(event, offLX, offLY);
		}

	}
	
	function docMouseMove(event, offLX, offLY){

		if(_this.mouseWhere == 'canvas'){
			//container.style.left = event.clientX - offLX; //设置block的X坐标 
			//container.style.top = event.clientY - offLY; //设置block的Y坐标 
			_this.rectInfo.x = offLX;
			_this.rectInfo.y = offLY;
			_this.rectInfo.w = event.offsetX - offLX;
			_this.rectInfo.h = event.offsetY - offLY;
			_this.kit.clearCanvas(_this.ctrlCanvas);
			//clearRect(ctrlCanvas, offLX, offLY,prevWidth, prevWidth);
			createRect(_this.ctrlCanvas,  _this.rectInfo, _this.maxWidth, _this.maxHeight);
			
			if(_this.rectInfo.w < 0){
				_this.rectInfo.x = _this.rectInfo.x+_this.rectInfo.w;
				_this.rectInfo.w = -_this.rectInfo.w;
			}
			if(_this.rectInfo.h<0){
				_this.rectInfo.y = _this.rectInfo.y+_this.rectInfo.h;
				_this.rectInfo.h = -_this.rectInfo.h;
			}

		}
	}


	document.onmouseup = function() {

		document.onmousemove = null;
		if(_this.mouseWhere == "canvas"){
			createSelectorDiv();
			
		}else if(_this.mouseWhere == 'rectDiv'){
			_this.rectInfo = newRectInfo;
			removeTip();
			//wrapper.removeChild(document.getElementById("plugin-110201-tip"));
		}

	} //end on mouse up

	// 创建选取框
	function createSelectorDiv(){
		_this.selectorDiv=rectDiv = document.createElement("div");

		_this.kit.addCss(rectDiv, {"border": "1px dashed #fff", "position":"absolute", "z-index": "4", "left": _this.rectInfo.x+"px", "top":_this.rectInfo.y+"px", "width": _this.rectInfo.w+"px", "height":_this.rectInfo.h+"px"});

		var upLeftDiv = document.createElement("div");
		_this.kit.addCss(upLeftDiv, {"width": "8px", "height": "8px",  "border": "1px solid #fff", "position":"absolute","top":"-5px", "left":"-5px", "cursor":"nw-resize", "z-index": "5"});
		rectDiv.appendChild(upLeftDiv);

		var upCenterDiv = document.createElement("div");
		_this.kit.addCss(upCenterDiv, {"width": "8px", "height": "8px",  "border": "1px solid #fff", "position":"absolute","top":"-5px", "left":"50%", "cursor":"n-resize", "z-index": "5"});
		rectDiv.appendChild(upCenterDiv);

		var upRightDiv = document.createElement("div");
		_this.kit.addCss(upRightDiv, {"width": "8px", "height": "8px",  "border": "1px solid #fff", "position":"absolute","top":"-5px", "right":"-5px", "cursor":"ne-resize", "z-index": "5"});
		rectDiv.appendChild(upRightDiv);

		var centerLeftDiv = document.createElement("div");
		_this.kit.addCss(centerLeftDiv, {"width": "8px", "height": "8px",  "border": "1px solid #fff", "position":"absolute","top":"50%", "left":"-5px", "cursor":"w-resize", "z-index": "5"});
		rectDiv.appendChild(centerLeftDiv);   

		var centerRightDiv = document.createElement("div");
		_this.kit.addCss(centerRightDiv, {"width": "8px", "height": "8px",  "border": "1px solid #fff", "position":"absolute","top":"50%", "right":"-5px", "cursor":"e-resize", "z-index": "5"});
		rectDiv.appendChild(centerRightDiv);  

		var bottomLeftDiv = document.createElement("div");
		_this.kit.addCss(bottomLeftDiv, {"width": "8px", "height": "8px",  "border": "1px solid #fff", "position":"absolute","bottom":"-5px", "left":"-5px", "cursor":"sw-resize", "z-index": "5"});
		rectDiv.appendChild(bottomLeftDiv);

		var bottomCenterDiv = document.createElement("div");
		_this.kit.addCss(bottomCenterDiv, {"width": "8px", "height": "8px",  "border": "1px solid #fff", "position":"absolute","bottom":"-5px", "left":"50%", "cursor":"s-resize", "z-index": "5"});
		rectDiv.appendChild(bottomCenterDiv);

		var bottomRightDiv = document.createElement("div");
		_this.kit.addCss(bottomRightDiv, {"width": "8px", "height": "8px",  "border": "1px solid #fff", "position":"absolute","bottom":"-5px", "right":"-5px", "cursor":"se-resize", "z-index": "5"});
		rectDiv.appendChild(bottomRightDiv);

		_this.wrapper.appendChild(rectDiv);

		setTimeout(function(){
			upLeftDiv.onmousedown = function(e){
				onDragDown(e, "nw", upLeftDiv);
				document.onmousemove = onDragMove;
			}
			
			upCenterDiv.onmousedown = function(e){
				onDragDown(e, "n", upCenterDiv);
				document.onmousemove = onDragMove;
			}
			
			upRightDiv.onmousedown = function(e){
				onDragDown(e, "ne", upRightDiv);
				document.onmousemove = onDragMove;
			}
			
			centerLeftDiv.onmousedown = function(e){
				onDragDown(e, "w", centerLeftDiv);
				document.onmousemove = onDragMove;
			}
			
			centerRightDiv.onmousedown = function(e){
				onDragDown(e, "e", centerRightDiv);
				document.onmousemove = onDragMove;
			}
			
			bottomLeftDiv.onmousedown = function(e){
				onDragDown(e, "sw", bottomLeftDiv);
				document.onmousemove = onDragMove;
			}

			bottomCenterDiv.onmousedown = function(e){
				onDragDown(e, "s", bottomCenterDiv);
				document.onmousemove = onDragMove;
			}

			bottomRightDiv.onmousedown = function(e){
				onDragDown(e, "se", bottomRightDiv);
				document.onmousemove = onDragMove;
			}
			
		}, 500)

	}


	//鼠标按下事件
	function onDragDown(e, type, div){
		
		_this.mouseWhere = "rectDiv";
		e = e || window.event;
		var location = _this.kit.getLocation(e);
		
		_this.currSelectorInfo.x = location.x;
		_this.currSelectorInfo.y = location.y;
		_this.currSelectorInfo.type = type;
		createTip({x: e.pageX, y: e.pageY, w:_this.rectInfo.w, h: _this.rectInfo.h});
		
	}
	
	
	var newRectInfo = {};
	function onDragMove (e) {
		
		newRectInfo = {x: _this.rectInfo.x, y: _this.rectInfo.y, w: _this.rectInfo.w, h: _this.rectInfo.h};
		if(_this.mouseWhere == 'rectDiv'){
			e = e || window.event;
			var location = _this.kit.getLocation(e);
			switch (_this.currSelectorInfo.type) {
				case "n":
					newRectInfo=move("n", location, newRectInfo);
					break;
				case "s":
					newRectInfo=move("s", location, newRectInfo);
					break;
				case "w":
					newRectInfo=move("w", location, newRectInfo);
					break;
				case "e":
					newRectInfo=move("e", location, newRectInfo);
					break;
				case "nw":
					newRectInfo=move("n", location, newRectInfo);
					newRectInfo=move("w", location, newRectInfo);
					break;
				case "ne":
					newRectInfo=move("n", location, newRectInfo);
					newRectInfo=move("e", location, newRectInfo);
					break;
				case "sw":
					newRectInfo=move("s", location, newRectInfo);
					newRectInfo=move("w", location, newRectInfo);
					break;
				case "se":
					newRectInfo=move("s", location, newRectInfo);
					newRectInfo=move("e", location, newRectInfo);
					break;
			}

			_this.kit.clearCanvas(_this.ctrlCanvas);
			createRect(_this.ctrlCanvas, newRectInfo, _this.maxWidth, _this.maxHeight);
			_this.tip.move({x: e.pageX, y:e.pageY, w: newRectInfo.w, h:newRectInfo.h});
			
		}

	}; //end drag move

	function move(type, location, newRectInfo){
	
		switch (type) {
			case "e":
				var addLength = _this.currSelectorInfo.x - location.x;
				newRectInfo.w = newRectInfo.w - addLength;
				rectDiv.style.width=newRectInfo.w+"px";
				break;
			case "s":
				var addLength = _this.currSelectorInfo.y - location.y;
				newRectInfo.h = newRectInfo.h- addLength;
				rectDiv.style.height= newRectInfo.h +"px";
				break;
			case "w":
				var addLength = _this.currSelectorInfo.x - location.x;
				newRectInfo.w = newRectInfo.w + addLength;
				newRectInfo.x = newRectInfo.x - addLength;
				rectDiv.style.width=newRectInfo.w+"px";
				rectDiv.style.left =newRectInfo.x+"px"
				break;
			case "n":
				var addLength = _this.currSelectorInfo.y - location.y;
				newRectInfo.h = newRectInfo.h+addLength;
				newRectInfo.y = newRectInfo.y-addLength;
				rectDiv.style.height=newRectInfo.h+"px";
				rectDiv.style.top=newRectInfo.y+"px";
				break;
		}
		return newRectInfo;
	} //end move
	
	function createTip(rectInfo){
		var tipElement = document.createElement("div");
		_this.tip = {};
		_this.tip.element = tipElement;
		_this.tip.info = rectInfo;
		tipElement.id="plugin-tip-xx-"+Math.random();
		_this.kit.addCss(tipElement, {"display":"inline-block","position":"absolute", "z-index":"10", "top":(rectInfo.y)+"px", "left":rectInfo.y+"px", "color":"#eee", "font-size":"12px"});
		tipElement.innerText = "(x:"+rectInfo.x+", y:"+rectInfo.y+", width: "+rectInfo.w+", height: "+rectInfo.h+" )";
		document.body.appendChild(tipElement);
		_this.tip.move = function(rectInfo){
			_this.tip.element.innerText = "(x:"+rectInfo.x+", y:"+rectInfo.y+", width: "+rectInfo.w+", height: "+rectInfo.h+" )";
			_this.kit.addCss(_this.tip.element, {"top":rectInfo.y+"px", "left": rectInfo.x+"px"});
			_this.tip.info = rectInfo;
		}
	}
	
	function removeTip(){
		
		var children = document.body.children;
		var deletes = [];
		for(var i=0; i<children.length; i++){
			if(children[i].id.indexOf("plugin-tip-xx") > -1){
				deletes.push(children[i]);
			}
		}
		for(var index in deletes){
			document.body.removeChild(deletes[index]);
		}
		
			_this.tip = null;
	}

	//创建一个变宽矩形
	function createRect(canvas, rectInfo,  minWidth, minHeight){
		//console.log(x,y, width, height);
		var ctx=canvas.getContext("2d");
		//ctx.clearRect(0,0, minWidth,minHeight);  

		ctx.beginPath();
		ctx.fillStyle = "rgba(0,0,0,0.5)";
		//ctx.translate(x,y);
		ctx.fillRect(0,0,minWidth,minHeight);
		ctx.closePath();

		ctx.clearRect(rectInfo.x, rectInfo.y,rectInfo.w, rectInfo.h);  
	}

	return _this;
}